﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Sumen.Business;
using DevExpress.XtraEditors;
using Sumen.Business.Data;
using Sumen.Business.Factory;
using Sumen.Business.Permission;
using Sumen.Library.Classes.Common;
using Sumen.Library.Enum;
using Sumen.Model.Model;

namespace Sumen.GUI.Admin
{
    public partial class Frm_User_Edit : XtraForm
    {

        #region Property
        //private UserPresenter _userPresenter;
        //private SysRolePresenter _sysRolePresenter;
        private EnumFormCode _fromCode = EnumFormCode.FrmUser;

        private EnumFormStatus _enumFormStatus;
        private user _user;
        private List<userrole> listUserRole;
        public user User
        {
            get { return _user; }
            set { _user = value; }
        }
        public EnumFormStatus EnumFormStatus
        {
            get { return _enumFormStatus; }
            set
            {
                _enumFormStatus = value;
                if (_enumFormStatus == EnumFormStatus.Add)
                {
                    buttonsArray1.btnSua.Enabled = false;
                    buttonsArray1.btnThem.Enabled = true;
                }
                else if (_enumFormStatus == EnumFormStatus.Modify)
                {
                    buttonsArray1.btnSua.Enabled = true;
                    buttonsArray1.btnThem.Enabled = false;
                }
            }
        }

        private Dao dao;
        private Dao daoTrans;
        #endregion

        /// <summary>
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>

        #region Form

        public Frm_User_Edit()
        {
            InitializeComponent();

            buttonsArray1.capQuyen(new Permission(_fromCode.ToString(), ClsPublic.User.User_Username));
            dao = new Dao();
            daoTrans = new Dao(false, true);
            //_userPresenter = new UserPresenter();
            // _sysRolePresenter = new SysRolePresenter();
        }

        private void Frm_User_Edit_Load(object sender, EventArgs e)
        {
            clbRole.DataSource = dao.GetAll<sys_role>();
            LoadForm();
        }

        #endregion

        /// <summary>
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>

        #region Button event

        private void buttonsArray1_btnEventAdd_click(object sender, EventArgs e)
        {
            if (Validation())
            {
                if (_enumFormStatus == EnumFormStatus.Add)
                {
                    EntityFactory.getInstance().BeginTransactionEntities();
                    //add
                    user newUser = addUser();
                    newUser.User_Password = ClsPublic.EncryptSHA512(newUser.User_Password);
                    newUser.User_CreationDate = DateTime.Now;
                    if (daoTrans.Add(newUser) > 0)
                    {
                        //tao danh sach module với quyền tương úng cho user đó
                        List<sys_object> listModule = dao.GetAll<sys_object>().ToList();
                        List<sys_user_permission> listPermissions = new List<sys_user_permission>();
                        listModule.ForEach(p =>
                        {
                            var per = new Permission(p.Syso_ID, newUser.User_Username);
                            listPermissions.Add(new sys_user_permission()
                            {
                                UP_User_ID = newUser.User_Username,
                                UP_Object_ID = p.Syso_ID,
                                UP_Permission = per.PermissionAll()
                            });
                        });
                        if (daoTrans.AddRange(listPermissions.ToArray()) > 0)
                        {
                            EntityFactory.getInstance().commit();
                            ClsMsgBox.ThongTin("Thêm mới tài khoản thành công");
                            ClsPublic.WriteLog(_fromCode, EnumFormStatus.Add, newUser.User_Username, "");
                            User = newUser;
                            this.EnumFormStatus = EnumFormStatus.Modify;
                        }
                    }
                    else
                    {
                        EntityFactory.getInstance().rollBack();
                    }




                    //if (_userPresenter.Add(newUser) > 0)
                    //{
                    //    ClsMsgBox.ThongTin("Thêm mới tài khoản thành công");
                    //    ClsPublic.WriteLog(_fromCode, EnumFormStatus.Add, newUser.User_Username, "");
                    //    User = newUser;
                    //    this.EnumFormStatus = EnumFormStatus.Modify;
                    //}
                }
            }
        }

        private void buttonsArray1_btnEventUpdate_click(object sender, EventArgs e)
        {
            update();

        }


        private void buttonsArray1_btnEventClose_click(object sender, EventArgs e)
        {
            this.Hide();
        }

        #endregion

        /// <summary>
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>


        #region MEthod

        void LoadForm()
        {
            if (_enumFormStatus == EnumFormStatus.Add)
            {
                txtUsername.EditValue = null;
                txtUsername.Properties.ReadOnly = false;
                txtUsername.EditValue = null;
                txtPass.EditValue = null;
                txtFullName.EditValue = null;
                txtPhone.EditValue = null;
                txtAddress.EditValue = null;
                txtContact.EditValue = null;
                txtEmail.EditValue = null;
                dateCreationDate.EditValue = null;
                dateLastChangePass.EditValue = null;
                dateLastLogin.EditValue = null;
                chkActived.CheckState = CheckState.Checked;
            }
            else if (_enumFormStatus == EnumFormStatus.Modify)
            {
                txtUsername.EditValue = _user.User_Username;
                txtUsername.Properties.ReadOnly = true;
                txtPass.EditValue = null;
                txtFullName.EditValue = _user.User_FullName;
                txtPhone.EditValue = _user.User_Phone;
                txtAddress.EditValue = _user.User_Address;
                txtContact.EditValue = _user.User_Contact;
                txtEmail.EditValue = _user.User_Email;
                chkActived.Checked = _user.User_Actived ?? false;
                dateCreationDate.EditValue = _user.User_CreationDate;
                dateLastChangePass.EditValue = _user.User_LastChangePassword;
                dateLastLogin.EditValue = _user.User_LastLoginDate;
                var list = _user.userroles.ToArray();
                var listRoles = ((ICollection<sys_role>)clbRole.DataSource).ToArray();
                for (int i = 0; i < list.Length; i++)
                {
                    for (int j = 0; j < listRoles.Length; j++)
                    {
                        var av = clbRole.GetItem(j) as sys_role;
                        var awt = dao.GetById<sys_role>(list[i].UR_Role_Id);
                        if (av.Role_ID == awt.Role_ID)
                        {
                            clbRole.SetItemChecked(j, true);
                        }
                    }
                }
                //list.ForEach(p => items.Add(new CheckedListBoxItem(p, true)));
                var a = clbRole.CheckedItems;
            }
        }

        bool Validation()
        {
            dxErrorProvider1.ClearErrors();
            if (txtUsername.EditValue == null || txtUsername.EditValue == "")
            {
                dxErrorProvider1.SetError(txtUsername, "Vui lòng nhập tài khoản");
                return false;
            }
            if (_enumFormStatus == EnumFormStatus.Add)
            {
                if (txtPass.EditValue == null || txtPass.EditValue == "")
                {
                    dxErrorProvider1.SetError(txtPass, "Vui lòng nhập mật khẩu");
                    return false;
                }
            }
            if (txtFullName.EditValue == null || txtFullName.EditValue == "")
            {
                dxErrorProvider1.SetError(txtFullName, "Vui lòng nhập họ tên");
                return false;
            }

            return true;
        }

        user addUser()
        {
            user newUser = new user();
            newUser.User_Username = txtUsername.EditValue + string.Empty;
            newUser.User_Password = txtPass.EditValue + string.Empty;
            newUser.User_FullName = txtFullName.EditValue + string.Empty;
            newUser.User_Phone = txtPhone.EditValue + string.Empty;
            newUser.User_Address = txtAddress.EditValue + string.Empty;
            newUser.User_Contact = txtContact.EditValue + string.Empty;
            newUser.User_Email = txtEmail.EditValue + string.Empty;
            newUser.User_Actived = chkActived.CheckState == CheckState.Checked ? true : false;
            newUser.User_CreationDate = DateTime.Today;
            newUser.User_LastLoginDate = dateLastLogin.DateTime;
            newUser.User_LastChangePassword = dateLastChangePass.DateTime;
            listUserRole = new List<userrole>();
            foreach (var checkedItem in clbRole.CheckedItems)
            {
                sys_role role = checkedItem as sys_role;
                userrole userroles = new userrole()
                {
                    UR_Role_Id = role.Role_ID,
                    UR_Username = newUser.User_Username,
                    user = newUser,
                    //sys_role = role
                };
                listUserRole.Add(userroles);
            }
            newUser.userroles = listUserRole;
            return newUser;
        }

        private void update()
        {
            if (Validation())
            {
                if (_enumFormStatus == EnumFormStatus.Modify)
                {
                    EntityFactory.getInstance().BeginTransactionEntities();
                    user newUser = addUser();
                    var listRoleOld = dao.FindByMultiColumnOr<userrole>(new[] { "user" }, newUser.User_Username);
                    //delete role of user
                    foreach (var userroleOld in listRoleOld)
                    {
                        bool isDelete = true;
                        foreach (var userroleNew in newUser.userroles)
                        {
                            if (userroleOld.UR_Role_Id == userroleNew.UR_Role_Id)
                            {
                                isDelete = false;
                                newUser.userroles.Remove(userroleNew);
                                break;
                            }
                        }
                        if (isDelete)
                        {
                            daoTrans.Delete<userrole>(userroleOld.UR_Username, userroleOld.UR_Role_Id);
                        }
                    }
                    if (newUser.User_Password != "")
                    {
                        newUser.User_Password = ClsPublic.EncryptSHA512(newUser.User_Password);
                        newUser.User_LastChangePassword = DateTime.Today;
                    }
                    //update user and add role for user
                    if (daoTrans.Update(newUser) >= 0 && daoTrans.AddRange(newUser.userroles.ToArray()) >= 0)
                    {
                        //con delete
                        ClsMsgBox.ThongTin("Cập nhật tài khoản thành công");
                        ClsPublic.WriteLog(_fromCode, EnumFormStatus.Modify, newUser.User_Username, "");
                        EntityFactory.getInstance().commit();
                    }
                    else
                    {
                        EntityFactory.getInstance().rollBack();
                    }
                }
            }
        }


        #endregion







    }
}